<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>配置管理</title>
    <!-- Element UI CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 自定义CSS -->
    <link rel="stylesheet" href="../css/style.css">
    <!-- Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <!-- Element UI JS -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <!-- API请求管理 -->
    <script src="../js/api.js"></script>
    <!-- YAML处理库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-yaml/4.1.0/js-yaml.min.js"></script>
    <!-- CodeMirror (YAML编辑器) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.1/codemirror.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.1/theme/monokai.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.1/codemirror.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.1/mode/yaml/yaml.min.js"></script>
    <script>
        // 使用父窗口的全局变量作为API基础URL
        const API_BASE_URL = window.parent.appGlobal.API_BASE_URL || 'http://localhost:8088';
    </script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",Arial,sans-serif;
        }
        .box-card {
            margin: 15px;
        }
        .config-manager {
            height: 100%;
        }
        .editor-container {
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .yaml-editor {
            width: 100%;
            height: 400px;
            font-family: monospace;
        }
        .loading-container {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 40px;
        }
        .editor-actions, .form-actions {
            margin-top: 20px;
            text-align: right;
        }
        .config-changed-hint {
            color: #E6A23C;
            font-size: 13px;
            margin-left: 10px;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="config-manager">
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>配置管理</span>
                    <div style="float: right; display: flex; align-items: center;">
                        <el-select 
                            v-model="selectedCollection" 
                            placeholder="切换集合" 
                            size="small" 
                            @change="switchCollection"
                            style="margin-right: 10px; width: 180px;">
                            <el-option
                                v-for="item in collections"
                                :key="item.name"
                                :label="item.name"
                                :value="item.name">
                                <span style="float: left">{{ item.name }}</span>
                                <span style="float: right; font-size: 12px; color: #8492a6; margin-right: 20px">
                                    {{ item.document_count || 0 }}篇文档
                                </span>
                            </el-option>
                        </el-select>
                        <el-button style="padding: 3px 0" type="text" @click="refreshConfig">刷新</el-button>
                    </div>
                </div>
                <el-form label-position="top">
                    <el-form-item label="配置文件路径">
                        <el-input v-model="configPath" placeholder="config.yaml">
                            <el-button slot="append" @click="loadConfig">加载</el-button>
                        </el-input>
                    </el-form-item>
                </el-form>
                <div v-if="loading" class="loading-container">
                    <el-progress type="circle" :percentage="100" status="text">加载中...</el-progress>
                </div>
                <div v-else>
                    <el-alert
                        v-if="error"
                        :title="error"
                        type="error"
                        :closable="false"
                        show-icon>
                    </el-alert>
                    <div v-if="config">
                        <el-tabs v-model="activeTab">
                            <el-tab-pane label="表单配置" name="form">
                                <el-form :model="formConfig" label-position="top" size="small">
                                    <!-- 服务器配置部分 -->
                                    <el-divider content-position="left">服务器配置</el-divider>
                                    <el-row :gutter="20">
                                        <el-col :span="12">
                                            <el-form-item label="服务器主机名">
                                                <el-input v-model="formConfig.server.host" placeholder="localhost"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="服务器端口">
                                                <el-input-number v-model="formConfig.server.port" :min="1" :max="65535" style="width: 100%"></el-input-number>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row :gutter="20">
                                        <el-col :span="12">
                                            <el-form-item label="调试模式">
                                                <el-switch v-model="formConfig.server.debug"></el-switch>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="启用CORS">
                                                <el-switch v-model="formConfig.server.cors"></el-switch>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                    <!-- 数据库配置部分 -->
                                    <el-divider content-position="left">数据库配置</el-divider>
                                    <el-row :gutter="20">
                                        <el-col :span="12">
                                            <el-form-item label="内存模式">
                                                <el-switch v-model="formConfig.database.memory_mode"></el-switch>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="使用集合模式">
                                                <el-switch v-model="formConfig.database.use_collections"></el-switch>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row :gutter="20">
                                        <el-col :span="24">
                                            <el-form-item label="单一数据库路径">
                                                <el-input v-model="formConfig.database.single_db_path" placeholder="vectordb.sqlite"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row :gutter="20">
                                        <el-col :span="24">
                                            <el-form-item label="集合目录路径">
                                                <el-input v-model="formConfig.database.collections_dir" placeholder="collections"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row :gutter="20">
                                        <el-col :span="12">
                                            <el-form-item label="自动保存间隔(秒)">
                                                <el-input-number v-model="formConfig.database.auto_save_interval" :min="1" :max="3600" style="width: 100%"></el-input-number>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                    <!-- 嵌入模型配置部分 -->
                                    <el-divider content-position="left">嵌入服务配置</el-divider>
                                    <el-row :gutter="20">
                                        <el-col :span="24">
                                            <el-form-item label="嵌入服务提供商">
                                                <el-select v-model="formConfig.embedding.provider" style="width: 100%">
                                                    <el-option label="Ollama" value="ollama"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row :gutter="20">
                                        <el-col :span="12">
                                            <el-form-item label="Ollama 主机">
                                                <el-input v-model="formConfig.embedding.ollama.host" placeholder="localhost"></el-input>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="Ollama 端口">
                                                <el-input-number v-model="formConfig.embedding.ollama.port" :min="1" :max="65535" style="width: 100%"></el-input-number>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row :gutter="20">
                                        <el-col :span="24">
                                            <el-form-item label="Ollama 模型">
                                                <el-select v-model="formConfig.embedding.ollama.model" style="width: 100%">
                                                    <el-option label="BGE-M3" value="bge-m3"></el-option>
                                                    <el-option label="All-MiniLM" value="all-minilm"></el-option>
                                                    <el-option label="Nomic-Embed" value="nomic-embed"></el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                                    <!-- Web界面配置部分 -->
                                    <el-divider content-position="left">Web界面配置</el-divider>
                                    <el-row :gutter="20">
                                        <el-col :span="12">
                                            <el-form-item label="提供静态文件服务">
                                                <el-switch v-model="formConfig.web.serve_static"></el-switch>
                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="12">
                                            <el-form-item label="根路径重定向到Web界面">
                                                <el-switch v-model="formConfig.web.redirect_root"></el-switch>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row :gutter="20">
                                        <el-col :span="24">
                                            <el-form-item label="静态文件目录">
                                                <el-input v-model="formConfig.web.static_dir" placeholder="./web"></el-input>
                                            </el-item>
                                        </el-col>
                                    </el-row>

                                    <div class="form-actions">
                                        <el-button type="primary" @click="saveConfigFromForm" :disabled="!configChanged">保存配置</el-button>
                                        <el-button @click="resetConfig" :disabled="!configChanged">重置</el-button>
                                        <span v-if="configChanged" class="config-changed-hint">* 配置已修改</span>
                                    </div>
                                </el-form>
                            </el-tab-pane>
                            <el-tab-pane label="YAML编辑器" name="editor">
                                <div class="editor-container">
                                    <textarea ref="yamlEditor" class="yaml-editor"></textarea>
                                </div>
                                <div class="editor-actions">
                                    <el-button type="primary" @click="saveConfigFromEditor" :disabled="!editorChanged">保存配置</el-button>
                                    <el-button @click="resetEditor" :disabled="!editorChanged">重置</el-button>
                                    <span v-if="editorChanged" class="config-changed-hint">* 配置已修改</span>
                                </div>
                            </el-tab-pane>
                            <el-tab-pane label="说明" name="help">
                                <el-alert type="info" :closable="false">
                                    <p><strong>配置文件说明：</strong></p>
                                    <ul>
                                        <li><strong>服务器配置</strong>: 设置服务器主机名、端口、调试模式和CORS支持</li>
                                        <li><strong>数据库配置</strong>: 配置数据存储方式，包括内存模式、集合模式等</li>
                                        <li><strong>嵌入服务配置</strong>: 设置用于生成向量嵌入的服务，目前支持Ollama</li>
                                        <li><strong>Web界面配置</strong>: 配置静态文件服务等Web界面选项</li>
                                    </ul>
                                    <p><strong>注意：</strong> 配置修改后需要重启服务器才能生效。</p>
                                </el-alert>
                            </el-tab-pane>
                        </el-tabs>
                        <el-dialog
                            title="配置已保存"
                            :visible.sync="saveSuccess"
                            width="30%">
                            <span>配置已成功保存。要使配置生效，请重启服务器。</span>
                            <span slot="footer" class="dialog-footer">
                                <el-button type="primary" @click="saveSuccess = false">确定</el-button>
                            </span>
                        </el-dialog>
                    </div>
                </div>
            </el-card>
        </div>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    configPath: 'config.yaml',
                    config: null,
                    originalConfig: null,
                    formConfig: {
                        server: {
                            host: 'localhost',
                            port: 8088,
                            debug: false,
                            cors: true
                        },
                        database: {
                            memory_mode: false,
                            single_db_path: 'vectordb.sqlite',
                            collections_dir: 'collections',
                            use_collections: true,
                            auto_save_interval: 300
                        },
                        embedding: {
                            provider: 'ollama',
                            ollama: {
                                host: 'localhost',
                                port: 11434,
                                model: 'bge-m3'
                            }
                        },
                        web: {
                            serve_static: true,
                            static_dir: './web',
                            redirect_root: true
                        }
                    },
                    originalFormConfig: null,
                    editor: null,
                    loading: false,
                    error: null,
                    activeTab: 'form',
                    saveSuccess: false,
                    configChanged: false,
                    editorChanged: false,
                    collections: [],
                    selectedCollection: ''
                }
            },
            
            mounted() {
                this.loadConfig();
                this.loadCollections();
            },
            
            watch: {
                'formConfig': {
                    handler: function(newVal) {
                        if (!this.originalFormConfig) return;
                        this.configChanged = JSON.stringify(newVal) !== JSON.stringify(this.originalFormConfig);
                        
                        // 如果是表单模式修改了配置，同步更新编辑器内容
                        if (this.editor && this.activeTab === 'form' && this.configChanged) {
                            this.editor.setValue(jsyaml.dump(this.formConfig));
                        }
                    },
                    deep: true
                }
            },
            
            methods: {
                // 加载配置
                loadConfig() {
                    this.loading = true;
                    this.error = null;
                    
                    axios.get(`${API_BASE_URL}/config?path=${this.configPath}`)
                        .then(response => {
                            this.config = response.data;
                            this.originalConfig = response.data;
                            
                            try {
                                // 解析YAML
                                const parsedConfig = jsyaml.load(this.config);
                                this.formConfig = this.normalizeConfig(parsedConfig);
                                this.originalFormConfig = JSON.parse(JSON.stringify(this.formConfig));
                            } catch (e) {
                                this.error = `解析配置失败: ${e.message}`;
                            }
                            
                            // 初始化或更新编辑器
                            this.$nextTick(() => {
                                if (!this.editor) {
                                    this.initYamlEditor();
                                } else {
                                    this.editor.setValue(this.config);
                                }
                                this.configChanged = false;
                                this.editorChanged = false;
                            });
                        })
                        .catch(error => {
                            console.error('获取配置失败:', error);
                            this.error = error.response?.data?.error || error.message || '获取配置失败';
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                },
                
                // 确保配置对象结构完整
                normalizeConfig(config) {
                    const defaultConfig = {
                        server: {
                            host: 'localhost',
                            port: 8088,
                            debug: false,
                            cors: true
                        },
                        database: {
                            memory_mode: false,
                            single_db_path: 'vectordb.sqlite',
                            collections_dir: 'collections',
                            use_collections: true,
                            auto_save_interval: 300
                        },
                        embedding: {
                            provider: 'ollama',
                            ollama: {
                                host: 'localhost',
                                port: 11434,
                                model: 'bge-m3'
                            }
                        },
                        web: {
                            serve_static: true,
                            static_dir: './web',
                            redirect_root: true
                        }
                    };
                    
                    // 深度合并配置
                    return {
                        server: {...defaultConfig.server, ...config?.server},
                        database: {...defaultConfig.database, ...config?.database},
                        embedding: {
                            ...defaultConfig.embedding,
                            ...config?.embedding,
                            ollama: {...defaultConfig.embedding.ollama, ...config?.embedding?.ollama}
                        },
                        web: {...defaultConfig.web, ...config?.web}
                    };
                },
                
                // 初始化YAML编辑器
                initYamlEditor() {
                    // 使用CodeMirror作为YAML编辑器
                    this.editor = CodeMirror.fromTextArea(this.$refs.yamlEditor, {
                        mode: 'yaml',
                        theme: 'monokai',
                        lineNumbers: true,
                        lineWrapping: true,
                        tabSize: 2,
                        extraKeys: {
                            "Tab": function(cm) {
                                var spaces = Array(cm.getOption("tabSize") + 1).join(" ");
                                cm.replaceSelection(spaces);
                            }
                        }
                    });
                    
                    this.editor.setValue(this.config);
                    this.editor.setSize('100%', '400px');
                    
                    // 监听变化
                    this.editor.on('change', () => {
                        this.editorChanged = this.editor.getValue() !== this.originalConfig;
                        
                        // 如果是编辑器模式修改了配置，尝试解析并更新表单
                        if (this.activeTab === 'editor' && this.editorChanged) {
                            try {
                                const editorContent = this.editor.getValue();
                                const parsedContent = jsyaml.load(editorContent);
                                // 先断开watch监听，再更新表单配置
                                this.formConfig = this.normalizeConfig(parsedContent);
                            } catch (e) {
                                // 解析失败不更新表单
                                console.error('解析YAML失败:', e);
                            }
                        }
                    });
                },
                
                // 从表单保存配置
                saveConfigFromForm() {
                    try {
                        // 将表单对象转换为YAML
                        const yamlContent = jsyaml.dump(this.formConfig);
                        this.saveConfigContent(yamlContent);
                    } catch (e) {
                        this.$message.error(`生成YAML失败: ${e.message}`);
                    }
                },
                
                // 从编辑器保存配置
                saveConfigFromEditor() {
                    const yamlContent = this.editor.getValue();
                    try {
                        // 验证YAML格式
                        jsyaml.load(yamlContent);
                        this.saveConfigContent(yamlContent);
                    } catch (e) {
                        this.$message.error(`YAML格式不正确: ${e.message}`);
                    }
                },
                
                // 保存配置内容
                saveConfigContent(content) {
                    axios.put(`${API_BASE_URL}/config?path=${this.configPath}`, content, {
                        headers: {
                            'Content-Type': 'text/plain'
                        }
                    })
                    .then(response => {
                        this.saveSuccess = true;
                        this.originalConfig = content;
                        this.originalFormConfig = JSON.parse(JSON.stringify(this.formConfig));
                        this.configChanged = false;
                        this.editorChanged = false;
                        
                        // 同步更新编辑器内容
                        if (this.editor) {
                            this.editor.setValue(content);
                        }
                    })
                    .catch(error => {
                        console.error('保存配置失败:', error);
                        this.$message.error(error.response?.data?.error || error.message || '保存配置失败');
                    });
                },
                
                // 刷新配置
                refreshConfig() {
                    if (this.configChanged || this.editorChanged) {
                        this.$confirm('当前有未保存的修改，确定要刷新吗？', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            this.loadConfig();
                        }).catch(() => {});
                    } else {
                        this.loadConfig();
                    }
                },
                
                // 重置表单配置
                resetConfig() {
                    this.formConfig = JSON.parse(JSON.stringify(this.originalFormConfig));
                    this.configChanged = false;
                    
                    // 同步重置编辑器
                    if (this.editor) {
                        this.editor.setValue(this.originalConfig);
                        this.editorChanged = false;
                    }
                },
                
                // 重置编辑器
                resetEditor() {
                    if (this.editor) {
                        this.editor.setValue(this.originalConfig);
                        this.editorChanged = false;
                        
                        // 重新解析编辑器内容到表单
                        try {
                            const parsedConfig = jsyaml.load(this.originalConfig);
                            this.formConfig = this.normalizeConfig(parsedConfig);
                            this.configChanged = false;
                        } catch (e) {
                            console.error('解析YAML失败:', e);
                        }
                    }
                },

                // 加载集合
                loadCollections() {
                    axios.get(`${API_BASE_URL}/collections`)
                        .then(response => {
                            this.collections = response.data.collections || [];
                            // 设置当前选中的集合
                            if (window.parent.appGlobal.activeCollection) {
                                this.selectedCollection = window.parent.appGlobal.activeCollection.name;
                            }
                        })
                        .catch(error => {
                            console.error('获取集合失败:', error);
                            this.$message.error(error.response?.data?.error || error.message || '获取集合失败');
                        });
                },

                // 切换集合
                switchCollection(collectionName) {
                    const collection = this.collections.find(item => item.name === collectionName);
                    if (collection) {
                        this.loading = true;
                        // 通知后端切换集合
                        axios.post(`${API_BASE_URL}/collections/${collectionName}/use`)
                            .then(() => {
                                // 更新父窗口全局变量
                                window.parent.appGlobal.activeCollection = collection;
                                this.$message({
                                    message: `已切换到集合: ${collection.name}`,
                                    type: 'success'
                                });
                            })
                            .catch(error => {
                                console.error('切换集合失败:', error);
                                this.$message.error('切换集合失败: ' + (error.response?.data?.error || error.message));
                                // 回退选中的集合
                                this.selectedCollection = window.parent.appGlobal.activeCollection?.name;
                            })
                            .finally(() => {
                                this.loading = false;
                            });
                    }
                }
            }
        });
    </script>
</body>
</html>